package com.westar.base.businessUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.westar.core.conf.SysConst;
import com.westar.base.util.JsoupSelfUtil;
import com.westar.base.util.WestarHttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ViewTaskUtil {

    public static Map<String, String> getSearchParamForViewTask(String html) {
        Map<String, String> result = new HashMap<>();
        String str = html.replace("\r\n", ""); //这里是为了解决 无法多行匹配的问题

        //获得参数taskId
        String regixTask = "var taskId_ =\\ (.*?);"; //()必须加，
        Pattern patternTask = Pattern.compile(regixTask,Pattern.MULTILINE);
        Matcher matcherTask = patternTask.matcher(str);
        if(matcherTask.find()){
            String option_1 = matcherTask.group();
            String taskId = option_1.replace( "var taskId_ = ","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\"","" )
                    .trim();

            result.put( "taskId",taskId );
        }

        //获得参数busiId
        String regixBusiId = "var affairId =\\ (.*?);"; //()必须加，
        Pattern patternBusiId = Pattern.compile(regixBusiId,Pattern.MULTILINE);
        Matcher matcherBusiId = patternBusiId.matcher(str);
        if(matcherBusiId.find()){
            String option_1 = matcherBusiId.group();
            String busiId = option_1.replace( "var affairId =","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\"","" )
                    .trim();
            result.put( "busiId",busiId );
        }

        //获得参数shardKey
        String regixShardKey = "var shardKey_ =\\ (.*?);"; //()必须加，
        Pattern patternShardKey = Pattern.compile(regixShardKey,Pattern.MULTILINE);
        Matcher matcherShardKey = patternShardKey.matcher(str);
        if(matcherShardKey.find()){
            String option_1 = matcherShardKey.group();
            String shardKey = option_1.replace( "var shardKey_ =","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\"","" )
                    .trim();
            result.put( "shardKey",shardKey );
        }
        //获得参数busiAlias
        String regixBusiAlias = "var busiAlias_ =\\ (.*?);"; //()必须加，
        Pattern patternBusiAlias = Pattern.compile(regixBusiAlias,Pattern.MULTILINE);
        Matcher matcherBusiAlias = patternBusiAlias.matcher(str);
        if(matcherBusiAlias.find()){
            String option_1 = matcherBusiAlias.group();
            String busiAlias = option_1.replace( "var busiAlias_ =","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\"","" )
                    .trim();
            result.put( "busiAlias",busiAlias );
        }

        return result;
    }

    /**
     * 普通办件界面
     * @param actCookie
     * @param wfTaskId
     * @param procTaskId
     * @param searchParam
     * @return
     * @throws Exception
     */
    public static String viewAffairTaskPage(String actCookie, String wfTaskId,String procTaskId,Map<String,String> searchParam) throws IOException {
        Map<String,String> result = new HashMap<String,String>(  );
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/viewTask/"+wfTaskId+"/"+procTaskId;
        String responeBody = WestarHttpUtil.getMethod(url,actCookie,searchParam);
        return responeBody;
    }

    /**
     * 场景办件界面
     * @param actCookie
     * @param taskId
     * @param searchParam
     * @return
     * @throws Exception
     */
    public static String viewCdSceneTaskPage(String actCookie, String taskId,Map<String,String> searchParam) throws IOException {
        Map<String,String> result = new HashMap<String,String>(  );
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/cdScene/viewTask/"+taskId;
        String responeBody = WestarHttpUtil.getMethod(url,actCookie,searchParam);
        return responeBody;
    }

    /**
     * 审批步骤界面
     * @param actCookie 唯一标识
     * @param searchParam 查询参数
     * @param submitType 提交类型
     * @return
     * @throws Exception
     */
    public static String getNextNodeInfo(String actCookie, Map<String, String> searchParam, String submitType) throws IOException {
        Map<String,String> result = new HashMap<String,String>(  );
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/workflow/commitTask4C";
        searchParam.put( "submitType",submitType );
        String responeBody = WestarHttpUtil.getMethod(url,actCookie,searchParam);
        return responeBody;

    }

    /**
     * 受理办件
     * @param actCookie 唯一标识
     * @param pageInfo 办件详情界面
     */
    public static void accept(String actCookie, String pageInfo ) throws IOException {

        Document doc = Jsoup.parse(pageInfo);
        Elements formDatas = doc.select("#affair_tab");
        if(null!= formDatas && !formDatas.isEmpty()) {
            String id = doc.select( "#id" ).attr( "value" );
            String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/handle/"+id+"/1";

            String taskId = doc.select( "#taskId" ).attr( "value" );

            Map<String,String> formParam = new HashMap<>(  );
            formParam.put("taskId",taskId);

            String responeBody = WestarHttpUtil.postMethod(url,actCookie,formParam);

            JSONObject res = JSONObject.parseObject(responeBody);
            ViewTaskUtil.submitTask(actCookie,"1",pageInfo);
        }
    }

    /**
     * 不予受理
     * @param actCookie 唯一标识
     * @param pageInfo 办件详情界面
     */
    public static void noAccept(String actCookie, String pageInfo ) throws IOException {

        Document doc = Jsoup.parse(pageInfo);
        Elements eleForm = doc.select("#affair_tab");
        Elements formDatas = eleForm.select( "div[title='基本信息']" );
        if(null!= formDatas && !formDatas.isEmpty()) {
            String id = formDatas.select( "#id" ).attr( "value" );
            String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/handle/"+id+"/1";

            String taskId = formDatas.select( "#taskId" ).attr( "value" );

            Map<String,String> formParam = new HashMap<>(  );
            formParam.put("taskId",taskId);

            String responeBody = WestarHttpUtil.postMethod(url,actCookie,formParam);

            //联审层级
            String tripleReviewLevelCode = formDatas.select( "#tripleReviewLevelCode" ).attr( "value" );
            //是否进行联审
            String isJointTrail = formDatas.select( "#isJointTrail" ).attr( "value" );
            if(StringUtils.isNotEmpty( tripleReviewLevelCode ) && StringUtils.isNotEmpty( isJointTrail ) && isJointTrail.equals( "1" )){
                //判断是否为三级联审件，如果是三级联审件则将另外层级的流程同样结束,批量结束流程
                batchJumpTask(actCookie,id);
            }else{
                // 结束流程
                String processInstanceId = formDatas.select( "#procInstId" ).attr( "value" );
                String procTaskId = formDatas.select( "#taskId" ).attr( "value" );
                String shardKey = formDatas.select( "#shardKey" ).attr( "value" );
                // 统一社会信用代码
                String busiDeptCode = formDatas.select( "#performDeptCode" ).attr( "value" );
                // 部门名称
                String busiDeptName = formDatas.select( "#implDeptName" ).attr( "value" );
                //当流程上没有配置人的时候，通过这个标志，为固定角色产生待办任务：1-依申请、2-主动行使
                String BIZ_PROP_DO_CASE_TYPE = "1";
                String callbackType = "0";
                Map<String,String> noacceptParam = new HashMap<String,String>( );
                noacceptParam.put("processInstanceId",processInstanceId );
                noacceptParam.put("procTaskId",procTaskId );
                noacceptParam.put("shardKey",shardKey );
                noacceptParam.put("busiDeptCode",busiDeptCode );
                noacceptParam.put("busiDeptName",busiDeptName );
                noacceptParam.put("BIZ_PROP_DO_CASE_TYPE",BIZ_PROP_DO_CASE_TYPE );
                noacceptParam.put("callbackType",callbackType );

                // 结束流程
                WorkflowUtil.jumpTask( actCookie,noacceptParam );
                // 保存不予受理的办理流水记录
                ViewTaskUtil.saveNoAcceptSteam(actCookie,"", "", "不予受理",formDatas);

            }

        }
    }

    /**
     * 保存不予受理的办理流水记录
     * @param actCookie
     * @param auditAdvice
     * @param auditAdviceName
     * @param auditRemark
     * @param formDatas
     * @return
     * @throws IOException
     */
    private static String saveNoAcceptSteam(String actCookie,String auditAdvice
            ,String auditAdviceName,String auditRemark, Elements formDatas) throws IOException {
        String busiId = formDatas.select( "#id" ).attr( "value" );
        String nodeId = formDatas.select( "#nodeId" ).attr( "value" );
        String nodeName = formDatas.select( "#nodeName" ).attr( "value" );
        String nodeType = formDatas.select( "#nodeType" ).attr( "value" );
        String esProcessDefId = formDatas.select( "#esProcessDefId" ).attr( "value" );
        String esActDefId = formDatas.select( "#esActDefId" ).attr( "value" );
        String esTaskId = formDatas.select( "#esTaskId" ).attr( "value" );
        String taskId = formDatas.select( "#taskId" ).attr( "value" );
        String esSource = formDatas.select( "#esSource" ).attr( "value" );
        String templetId = formDatas.select( "#templetId" ).attr( "value" );

        Map<String,String> postParam = new HashMap<String,String>();
        postParam.put("busiId",busiId  );
        postParam.put("nodeId",nodeId  );
        postParam.put("nodeName",nodeName  );
        postParam.put("nodeType",nodeType  );
        postParam.put("esProcessDefId",esProcessDefId  );
        postParam.put("esActDefId",esActDefId  );
        postParam.put("esTaskId",esTaskId  );
        postParam.put("taskId",taskId  );
        postParam.put("esSource",esSource  );
        postParam.put("templetId",templetId  );
        postParam.put("auditAdvice",auditAdvice  );
        postParam.put("auditAdviceName",auditAdviceName  );
        postParam.put("auditRemark",auditRemark  );

        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/submitTask/"+taskId;
        String responeBody = WestarHttpUtil.postMethod(url,actCookie ,postParam );
        return responeBody;

    }


    /**
     * 提交表单的后续工作
     * @param token 唯一标识
     * @param type 类型
     * @param document 页面数据
     */
    private static void doSubmitTaskAfter(String token, String type, Document document) throws IOException {
        String appendixSource = document.select( "#appendixSource" ).attr( "value" );
        String taskId  = document.select( "#taskId" ).attr( "value" );
        String nodeId  = document.select( "#nodeId" ).attr( "value" );
        String nextHandlerJSON_  = document.select( "#nextHandlerJSON_" ).attr( "value" );
        // 流程节点类型：申请受理、审查、决定、收费、制证、取件
        String wfNodeType = document.select( "#wfNodeType" ).attr( "value" );
        if(type.equals( "6" )){
            //受理并办结，结束流程
            // 结束流程
            Map<String,String> param = new HashMap<>( );
            String processInstanceId = document.select( "#procInstId " ).attr( "value" );
            String shardKey = document.select( "#shardKey" ).attr( "value" );
            // 统一社会信用代码
            String busiDeptCode = document.select( "#performDeptCode" ).attr( "value" );
            String busiDeptName = document.select( "#implDeptName" ).attr( "value" );
            // 当流程上没有配置人的时候，通过这个标志，为固定角色产生待办任务：1-依申请、2-主动行使
            String BIZ_PROP_DO_CASE_TYPE = "1";
            String callbackType = "0";
            param.put( "processInstanceId",processInstanceId );
            param.put( "procTaskId",taskId );
            param.put( "nextNodeId",nodeId );
            param.put( "nextHandler",nextHandlerJSON_ );

            param.put( "shardKey",shardKey );
            param.put( "busiDeptCode", busiDeptCode);
            param.put( "busiDeptName",busiDeptName );
            param.put( "BIZ_PROP_DO_CASE_TYPE",BIZ_PROP_DO_CASE_TYPE );
            param.put( "callbackType",callbackType );
            //
            WorkflowUtil.jumpTask( token,param );

        }else if(appendixSource.equals( "1" ) && wfNodeType.equals( "viewTask4SL" ) ){// // 如果受理节点，且是统一受理的办件，模拟提交任务
            ViewTaskUtil.completeTheTask(token,taskId);
        }else if(type.equals( "8" )){
            Map<String, String> resultIdea = ViewTaskUtil.getSpIdea(type,document);
            String auditAdvice = resultIdea.get("auditAdvice");
            String direct = auditAdvice.equals( "1" )?"":"no";// 根据建议，结束或者继续流程
            ViewTaskUtil.handleTask(token,direct,document);
        }else if(type.equals( "back" )){// 回退退回
            ViewTaskUtil.handleTask(token,type,document);
        }else{
            // 如果是办结节点，生成办结通知书
            String isBJNotice = document.select( "#isBJNotice" ).attr( "value" );
            String busiId =  document.select( "#id" ).attr( "value" );
            if(isBJNotice.equals( "true" )){
                String responeBody = ViewTaskUtil.generateAndViewBJNotice( token,busiId);
                ViewTaskUtil.preCompleteTask(token,null,document); // 准备提交任务
            }else if(wfNodeType.equals( "viewTask4YJHY" )){//如果是取件节点就会再次生成通知书并覆盖
                boolean success = ViewTaskUtil.generateAndViewBJNoticeForPickUp(token,busiId);
                if(success){
                    ViewTaskUtil.preCompleteTask(token,null,document);
                }
            }else{
                boolean success = ViewTaskUtil.preCompleteTask(token,null,document); // 准备提交任务
                if(success){
                    // 如果是受理节点，完成任务后创建三级联审、并联审批的单据
                    if(wfNodeType .equals( "viewTask4SL" )){
                        //三级联审创建单据
                        ViewTaskUtil.createTripleReview(token,document);
                        //并联审批
                        ViewTaskUtil.createParallel(token,document);
                    }

                }

            }
        }
    }

    /**
     * 受理
     * @param actCookie 访问的唯一标识
     * @param type 类型
     * @param pageInfo 办件详情页面
     */
    public static void submitTask( String actCookie, String type,String pageInfo) throws IOException {

        Document document = Jsoup.parse(pageInfo);
        Map<String,String> submitTaskParam = ViewTaskUtil.getSubmitTaskParam(document,type);

        String havePickup = document.select( "#havePickup" ).attr( "value" );

        String jdStatus = document.select( "#jdStatus" ).attr( "value" );

        //1：现场取件，2：物流
        Elements pickupTypeRadio = document.select("input[name='pickupType']");
        String pickupType = JsoupSelfUtil.getRadioVal(pickupTypeRadio);

        boolean saveLogistics = false;

        Map<String,String> pickParam = null;
        //添加判断   如果是不予受理的件并且是现场申请的件  必须填写现场申请的 取件人信息
        if (type.equals( "10" ) && havePickup.equals( "true" ) && pickupType.equals( "1" )) {
            //取件环节 取件人信息
            pickParam = ViewTaskUtil.getPickParam(document,type);

            String saveLogisticsUrl = "http://"+ SysConst.DOMAIN+"/dothingsui/affariLogistical/saveLogistics";
            WestarHttpUtil.postMethod(saveLogisticsUrl,actCookie,pickParam);
        }
        if(jdStatus.equals( "1" )){
            //决定节点保存物流信息
            pickParam = ViewTaskUtil.getPickParam(document,type);
            String saveLogisticsUrl = "http://"+ SysConst.DOMAIN+"/dothingsui/affariLogistical/saveLogistics";
            WestarHttpUtil.postMethod(saveLogisticsUrl,actCookie,pickParam);
        }
        //是否需要支付信息
        boolean isSubmit = ViewTaskUtil.getCanSubmit(actCookie,document);

        if(isSubmit){
            String taskId = document.select( "#taskId" ).attr( "value" );
            String url = "http://"+ SysConst.DOMAIN + "/dothingsui/affair/submitTask/" + taskId;
            String responeBody = WestarHttpUtil.postMethod(url,actCookie,submitTaskParam );
            JSONObject jsonObject = JSONObject.parseObject(responeBody);
            boolean success = jsonObject.getBoolean("success");
            if(success){
                ViewTaskUtil.doSubmitTaskAfter(actCookie,type,document);
            }

        }

    }

    private static Map<String, String> getPickParam(Document document, String type) {

        Map<String, String> result = new HashMap<>();
        //取件人姓名
        String recName = document.select( "#recName" ).attr( "value" );
        Elements recGenderRadio = document.select("input[name='recGender']");
        String recGender = JsoupSelfUtil.getRadioVal(recGenderRadio);
        //联系人证件号
        String applicantIdCard = document.select( "#identityCode" ).attr( "value" );
        //取件时间
        String createTime = document.select( "#createTime" ).attr( "value" );
        //取件人联系电话
        String recPhone = document.select( "#recPostalCode" ).attr( "value" );
        String applyType = document.select( "#applyType" ).attr( "value" );
        String havePickup = document.select( "#havePickup" ).attr( "value" );

        Elements pickupTypeRadio = document.select("input[name='pickupType']");
        String pickupType = JsoupSelfUtil.getRadioVal(pickupTypeRadio);

        String recAddress = document.select( "#recAddress" ).attr( "value" );

        String jdStatus = document.select( "#jdStatus" ).attr( "value" );
        if(StringUtils.isNotEmpty(jdStatus) && jdStatus.equals( "1" )){
            String pickUpInfoName = document.select( "#pickUpInfoName" ).attr( "value" );
            String pickUpInfoContactPhone  = document.select( "#pickUpInfoContactPhone" ).attr( "value" );
            String pickUpInfoIdCardNumber  = document.select( "#pickUpInfoIdCardNumber" ).attr( "value" );
            String pickUpInfoTime  = document.select( "#pickUpInfoTime" ).attr( "value" );
            String pickUpInfoAddress  = document.select( "#pickUpInfoAddress" ).attr( "value" );

            recName = pickUpInfoName;
            recPhone = pickUpInfoContactPhone;
            applicantIdCard = pickUpInfoIdCardNumber;
            createTime = pickUpInfoTime;
            recAddress = pickUpInfoAddress;

        }

        String affairId = document.select( "#id" ).attr( "value" );
        String shardKey = document.select( "#shardKey" ).attr( "value" );
        String affairCode = document.select( "#affairCode" ).attr( "value" );
        String applicantName = document.select( "#applicantName" ).attr( "value" );
        String eventName = document.select( "#eventName" ).attr( "value" );
        String eventType = document.select( "#eventType" ).attr( "value" );
        String recAddrProvince = document.select( "#recAddrProvince" ).attr( "value" );
        String recAddrCity = document.select( "#recAddrCity" ).attr( "value" );
        String recAddrCounty = document.select( "#recAddrCounty" ).attr( "value" );
        String postalCode = document.select( "#postalCode" ).attr( "value" );

        result.put("affairId",affairId);
        result.put("recName",recName);
        result.put("recGender",recGender);
        result.put("applicantIdCard",applicantIdCard);
        result.put("createTime",createTime);
        result.put("shardKey",shardKey);
        result.put("affairCode",affairCode);
        result.put("applicantName",applicantName);
        result.put("eventName",eventName);
        result.put("eventType",eventType);
        result.put("recPhone",recPhone);
        result.put("recAddrProvince",recAddrProvince);
        result.put("recAddrCity",recAddrCity);
        result.put("recAddrCounty",recAddrCounty);
        result.put("recAddress",recAddress);
        result.put("postalCode",postalCode);
        return result;


    }

    /**
     * 模拟完成任务并推送数据给厅局
     * @param actCookie
     * @param taskId
     */
    private static void completeTheTask(String actCookie, String taskId) throws IOException {
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/completeTheTask";
        Map<String,String> formParam = new HashMap<>(  );
        formParam.put("taskId",taskId );
        String responeBody = WestarHttpUtil.postMethod( url, actCookie, formParam );
    }

    private static void createParallel(String actCookie, Document document) throws IOException {
        String id = document.select( "#id" ).attr( "value" );
        //并联审批编码
        String affairParallelCode = document.select("#affairParallelCode").attr( "value" );
        //并联审批实施清单id集合
        String affairIdList = document.select("#affairIdList").attr( "value" );
        //并联审批主线
        String isThread = document.select("#isThread").attr( "value" );
        //1.并联审批编码 2.并联审批实施清单id集合不为空
        //1.联审层级信息不为空 2.需要进行联审 3.主线任务
        boolean state = StringUtils.isNotEmpty( affairParallelCode   )
                &&StringUtils.isNotEmpty(affairIdList) && isThread.equals( "1" );
        if(state){
            String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/createParallerl.do";
            Map<String,String> formParam = new HashMap<>(  );
            formParam.put( "affairId",id );
            formParam.put( "implementIds",affairIdList );
            String resStr = WestarHttpUtil.postMethod( url,actCookie,formParam );
            JSONObject reg = JSONObject.parseObject("resStr");
            boolean successes = reg.getBoolean( "successes");
            if(successes){
                //并联审批，主线受理之后为别的层级生成单据并且创建流程实例
                //创建并联审批单据
                 JSONArray affairList = reg.getJSONArray("listData");
                if(null!=affairList && affairList.isEmpty()) {
                    for (Object affairObj : affairList) {
                        JSONObject affairto = JSONObject.parseObject( affairObj.toString() );
                        Map<String, String> param = ViewTaskUtil.createParallelAfter( affairto );
                        //为并联审批的层级启用流程
                        String responeBody = WorkflowUtil.createAndStartUpProcess( actCookie,param );
                        JSONObject res = JSONObject.parseObject(responeBody);
                        boolean succcess = res.getBoolean("success" );
                        if(succcess){
                            Map<String,String> data = new HashMap<>(  );
                            data.put( "wfInstanceId", res.getString( "procInstId" ));
                            data.put( "shardKey",affairto.getString( "shardKey" ) );
                            ViewTaskUtil.createParallelProcess(actCookie,affairto.getString( "idForStr" ),"4",data );
                        }
                    }
                }

            }
        }
    }

    private static Map<String, String> createParallelAfter(JSONObject affairdto) {
        Map<String, String> param = new HashMap<>( );
        param.put( "busiId",affairdto.getString("idForStr") );
        param.put( "busiAlias","COMMON-MODEL");
        // 是否第一个流程节点，用于判断是否自动跳过第一个节点任务
        param.put( "isFitstNodeAutoSubmit","true");

        param.put( "totalDue",affairdto.getString("promiseTimeLimit") );
        param.put( "procDefKey",affairdto.getString("wfTemplateKey") );
        param.put( "shardKey",affairdto.getString("shardKey") );
        param.put( "busiTitle",affairdto.getString("eventName") );
        param.put( "affairCode",affairdto.getString("affairCode") );
        param.put( "eventType",affairdto.getString("eventType") );
        param.put( "eventCode",affairdto.getString("eventCode") );
        param.put( "creatorName",affairdto.getString("creatorName") );
        param.put( "affairAuditType","3");
        param.put( "applicantName",affairdto.getString("applicantName") );
        param.put( "eventName",affairdto.getString("eventName") );
        param.put( "isParallel",affairdto.getString("isParallel") );
        param.put( "isMultilevel",affairdto.getString("isMultilevel") );
        param.put( "limitType",affairdto.getString("limitType") );
        param.put( "legalTimeLimit",affairdto.getString("legalTimeLimit") );
        param.put( "applyType",affairdto.getString("applyType") );
        param.put( "applicantIdCard",affairdto.getString("applicantIdCard") );
        param.put( "areaCode",affairdto.getString("implAreaCode") );
        param.put( "busiDeptCode",affairdto.getString("performDeptCode") );
        param.put( "busiDeptName",affairdto.getString("implDeptName") );
        param.put( "deptCode",affairdto.getString("implDeptCode") );
        param.put( "deptName",affairdto.getString("implDeptName") );
        param.put( "affairParallelCode",affairdto.getString("affairParallelCode") );
        param.put( "appendixSource",affairdto.getString("appendixSource") );
        param.put( "firstDeptCode",affairdto.getString("firstDeptCode") );
        param.put( "firstDeptName",affairdto.getString("firstDeptName") );
        param.put( "firstDeptSortKey",affairdto.getString("firstDeptSortKey") );
        param.put( "appoveTimeLimit",affairdto.getString("appoveTimeLimit") );

        String tem = affairdto.getString("rights");
        String busiType = affairdto.getString("busiType");
        // 综窗
        boolean state = StringUtils.isNotEmpty(busiType)
                && busiType.equals( "2" )
                && StringUtils.isNotEmpty(tem );
        if(state){
            param.put("ZCBJ_PARAM_IS_ZCBJ","1"); // 是否综窗办件:1-是,空活0-否
            param.put("ZCBJ_PARAM_DEPTCODE",affairdto.getString("bigDeptCode")); // 综窗办件_取件窗口,多个综窗以逗号[,]隔开                -->使用大部门编码替换部门编码  by yk
            param.put("ZCBJ_BUSI_TYPE", tem);// 综窗办件_取件窗口,多个综窗以逗号[,]隔开
        }

        return param;
    }

    /**
     * 创建三级联审单据
     * @param actCookie
     * @param document
     */
    private static void createTripleReview(String actCookie, Document document) throws IOException {

        String id = document.select( "#id" ).attr( "value" );
        String tripleReviewLevelCode = document.select("#tripleReviewLevelCode").attr( "value" );//联审层级

        Elements isJointTrailRadio = document.select("input[name='isJointTrail']");
        String isJointTrail = JsoupSelfUtil.getRadioVal(isJointTrailRadio);//是否进行联审
        String isThread = document.select("#isThread").attr( "value" );//是否进行联审
        //1.联审层级信息不为空 2.需要进行联审 3.主线任务
        boolean state = StringUtils.isNotEmpty( tripleReviewLevelCode  )
                && isJointTrail.equals( "1" ) && isThread.equals( "1" );
        if(state){
            String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/createTripleReview.do";
            Map<String,String> formParam = new HashMap<>(  );
            formParam.put( "affairId",id );
            formParam.put( "areaIds",tripleReviewLevelCode );
            String resStr = WestarHttpUtil.postMethod( url,actCookie,formParam );

            JSONObject jsonObject = JSONObject.parseObject("resStr");
            boolean successes = jsonObject.getBoolean( "successes");
            if(successes){
                //三级联审，主线受理之后为别的层级生成单据并且创建流程实例
                //创建三级联审单据
                JSONArray affairList = jsonObject.getJSONArray("listData");
                if(null!=affairList && affairList.isEmpty()){
                    for (Object affairObj  :affairList ) {
                        JSONObject affair = JSONObject.parseObject( affairObj.toString());
                        Map<String,String> param = ViewTaskUtil.createTripleReviewAfter(affair);

                        //为三级联审别的层级启用流程
                        String responeBody = WorkflowUtil.createAndStartUpProcess( actCookie, param );
                        JSONObject res = JSONObject.parseObject(responeBody);
                        boolean succcess = res.getBoolean("success" );
                        if(succcess){
                            Map<String,String> data = new HashMap<>(  );
                            data.put( "wfInstanceId", res.getString( "procInstId" ));
                            data.put( "shardKey",affair.getString( "shardKey" ) );
                            ViewTaskUtil.createParallelProcess(actCookie,affair.getString( "idForStr" ),"4",data );
                        }
                    }
                }


            }

        }

    }

    /**
     * 为并联审批别的层级启用流程
     * @param actCookie
     * @param id
     * @param type 1:已受理、-1：待补正补齐、-2：不予受理、0：已补正补齐、3: 便民中心上报、4：提交
     * @param data
     */
    private static void createParallelProcess(String actCookie, String id, String type, Map<String, String> data) throws IOException {
        String url = "http://"+ SysConst.DOMAIN + "/dothingsui/affair/handle/" + id + "/" + type;
        String responeBody = WestarHttpUtil.postMethod( url, actCookie, null );
        JSONObject jsonObject = JSON.parseObject(responeBody);

    }

    /**
     * 创建三级联审单据
     * @param affair
     * @return
     */
    private static Map<String, String> createTripleReviewAfter(JSONObject affair) {
        Map<String, String> param = new HashMap<>( );
        param.put("busiId",affair.getString("idForStr"));
        param.put("busiAlias","COMMON-MODEL");
        //// 是否第一个流程节点，用于判断是否自动跳过第一个节点任务
        param.put("isFitstNodeAutoSubmit","false");
        param.put("totalDue",affair.getString("promiseTimeLimit"));
        param.put("procDefKey",affair.getString("wfTemplateKey"));
        param.put("shardKey",affair.getString("shardKey"));
        param.put("busiTitle",affair.getString("eventName"));
        param.put("busiCode",affair.getString("affairCode"));
        param.put("affairCode",affair.getString("affairCode"));
        param.put("eventType",affair.getString("eventType"));
        param.put("eventCode",affair.getString("eventCode"));
        param.put("creatorName",affair.getString("creatorName"));
        param.put("affairAuditType","2");
        param.put("applicantName",affair.getString("applicantName"));
        param.put("eventName",affair.getString("eventName"));
        param.put("isParallel",affair.getString("isParallel"));
        param.put("isMultilevel",affair.getString("isMultilevel"));
        param.put("limitType",affair.getString("daysType"));
        param.put("legalTimeLimit",affair.getString("legalTimeLimit"));
        param.put("applyType",affair.getString("applyType"));
        param.put("applicantIdCard",affair.getString("applicantIdCard"));
        param.put("isJointTrail",affair.getString("isJointTrail"));
        param.put("affairParallelCode",affair.getString("affairParallelCode"));
        param.put("jointTrailCode",affair.getString("jointTrailCode"));
        param.put("isThread",affair.getString("isThread"));
        param.put("areaCode",affair.getString("implAreaCode"));
        param.put("busiDeptCode",affair.getString("performDeptCode")); //大部门编码
        param.put("busiDeptName",affair.getString("implDeptName"));// 大部门名称
        param.put("deptCode",affair.getString("implDeptCode"));//当前处理人直接部门编码
        param.put("deptName",affair.getString("implDeptName"));//当前处理人直接部门名称
        param.put("appendixSource",affair.getString("appendixSource"));
        param.put("firstDeptCode",affair.getString("firstDeptCode"));
        param.put("firstDeptName",affair.getString("firstDeptName"));
        param.put("firstDeptSortKey",affair.getString("firstDeptSortKey"));
        param.put("appoveTimeLimit",affair.getString("appoveTimeLimit"));

        String busiType = affair.getString("busiType");
        // 综窗
        if(StringUtils.isNotEmpty(busiType ) && busiType.equals( "2" )){
            String isJointTrail = affair.getString("isJointTrail");
            if(StringUtils.isNotEmpty( isJointTrail) && isJointTrail.equals( "1" )){
                //是否第一个流程节点，用于判断是否自动跳过第一个节点任务(综合窗口跳过第一个节点,三级联审的不调过第一节点)
                param.put("isFitstNodeAutoSubmit","false");
            }else{
                // 是否第一个流程节点，用于判断是否自动跳过第一个节点任务(综合窗口跳过第一个节点)
                param.put("isFitstNodeAutoSubmit","true");
            }
            // 是否综窗办件:1-是,空活0-否
            param.put("ZCBJ_PARAM_IS_ZCBJ","1");
            // 综窗办件_取件窗口,多个综窗以逗号[,]隔开
            param.put("ZCBJ_PARAM_DEPTCODE",affair.getString("acceptDeptCode"));

        }
        return param;
    }

    private static boolean generateAndViewBJNoticeForPickUp(String actCookie, String busiId) throws IOException {
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/handle/"+busiId+"/7";
        String responeBody = WestarHttpUtil.postMethod(url,actCookie,null  );
        JSONObject jsonObject = JSONObject.parseObject(responeBody);
        boolean success = jsonObject.getBoolean("success");
        return success;

    }

    private static boolean getCanSubmit(String actCookie, Document document) throws IOException {
        boolean isSubmit = true;

        boolean pay = false;
        String wfNodeType = document.select( "#wfNodeType" ).attr( "value" );
        if (wfNodeType.equals("viewTask4SF")) {
            pay = true;
        }

        if(pay){
            //判断是否支付，是否是缓交，免缴 缓交，免缴，已经支付可以提交
            //ajax获取是否支付
            String id = document.select( "#id" ).attr( "value" );

            String payUrl = "http://"+ SysConst.DOMAIN+"/affairChargeInfo/getAllIsPay/" + id;
            String responeBody = WestarHttpUtil.getMethod( payUrl,actCookie,null );

            JSONObject jsonObject = JSONObject.parseObject(responeBody);
            isSubmit = jsonObject.getBoolean("isPay");

            if(!isSubmit){
                String shardKey = document.select( "#shardKey" ).attr( "value" );
                //收费项目
                //initChargeInfoList
                String affairChargeInfo = "http://"+ SysConst.DOMAIN+"/dothingsui/affairChargeInfo/listData";
                Map<String,String> postParam = new HashMap<String,String>();
                postParam.put( "affairId",id );
                postParam.put( "shardKey",shardKey );
                String responeChargeBody = WestarHttpUtil.postMethod(affairChargeInfo,actCookie ,postParam );
                JSONArray jsonArray = JSONArray.parseArray(responeChargeBody );
                if(null!=jsonArray && !jsonArray.isEmpty()){
                    for (Object obj:jsonArray){
                        JSONObject jsonChargeObject = JSONObject.parseObject(obj.toString());
                        String holdTime = jsonChargeObject.getString("holdTime");
                        String chargeType = jsonChargeObject.getString("chargeType");
                        if(StringUtils.isNotEmpty(holdTime)){
                            isSubmit = true;
                        }else if(chargeType.equals( "2" )){//设置免缴的时候可以提交 gandazhi
                            isSubmit = true;
                        }else{
                            isSubmit = false;
                            break;
                        }

                    }

                }

            }

        }

        return isSubmit;
    }

    /**
     * 取得用于提交表单的数据
     * @param document 表单页面
     * @param type
     * @return
     */
    private static Map<String, String> getSubmitTaskParam(Document document , String type) {

        Elements formDataExists = document.select( "#id" ).parents();

        Map<String, String> result = new HashMap<>(  );

        String busiId = formDataExists.select( "#id" ).attr( "value" );
        result.put("busiId",busiId);

        //相关数据
        String[] liushuiKeys = new String[]{"shardKey","templetId","nodeId","taskId","esheetId","nodeName",
                "nodeType","esSource","esProcessDefId","esActDefId","esTaskId"};
        for (String key:liushuiKeys ) {
            String value = formDataExists.select( "#"+key ).attr( "value" );
            result.put(key,value);
        }
        result.put("esheetValueJson","");

        //意见信息
        Map<String, String> resultIdea = ViewTaskUtil.getSpIdea(type,document);
        result.putAll(resultIdea);
        //表单其他数据
        Map<String, String> resultSpecial = ViewTaskUtil.getSpSpecialForTask(document,type);
        result.putAll(resultSpecial);

        //投资项目的表单
        String projectTempletId = document.select( "#pesTempletId" ).attr( "value" );
        result.put("projectTempletId",projectTempletId);
        String projectEsheetId = document.select( "#pesheetId" ).attr( "value" );
        result.put("projectEsheetId",projectEsheetId);



        return result;
    }

    /**
     * 取得特俗参数信息
     * @param document
     * @param type
     * @return
     */
    private static Map<String, String> getSpSpecialForTask(Document document, String type) {
        Map<String, String> result = new HashMap<>();
        if(type.equals( "8" )){
            String decisionRemark = document.select( "#decisionRemark" ).attr( "value" );
            result.put("decisionRemark",decisionRemark);
        }
        String eventType = document.select( "#eventType" ).attr( "value" );
        if(type.equals( "9" ) && eventType.equals( "1A" )){
            String licenseStartTime = document.select( "#licenseStartTime" ).attr( "value" );
            String licenseEndTime = document.select( "#licenseEndTime" ).attr( "value" );
            String licenseDocumentsNeme = document.select( "#handle input[id='licenseDocumentsNeme']" ).attr( "value" );
            String licenseDocumentsCode = document.select( "#handle input[id='licenseDocumentsCode']" ).attr( "value" );
            String licenseType = document.select( "#licenseTypes" ).attr( "value" );
            String licenseRemark = document.select( "#handle input[id='licenseRemark']" ).attr( "value" );
            String licenseCertificateNeme = document.select( "#handle input[id='licenseCertificateNeme']" ).attr( "value" );
            String licenseCertificateCode = document.select( "#handle input[id='licenseCertificateCode']" ).attr( "value" );
//            if (licenseStartTime == null || licenseStartTime == "") {
//                alert("未填写许可有效期开始时间!");
//                return;
//            }
//            if (licenseEndTime == null || licenseEndTime == "") {
//                alert("未填写许可有效期结束时间!");
//                return;
//            }
//            if (licenseDocumentsNeme == null || licenseDocumentsNeme == "") {
//                alert("未填写行政许可决定文书名称!");
//                return;
//            }
//            if (licenseDocumentsCode == null || licenseDocumentsCode == "") {
//                alert("未填写文书号!");
//                return;
//            }
//            if (licenseCertificateNeme == null || licenseCertificateNeme == "") {
//                alert("未填写行政许可证书名称!");
//                return;
//            }
//            if (licenseCertificateCode == null || licenseCertificateCode == "") {
//                alert("未填写行政许可证书编号!");
//                return;
//            }
//            if (licenseTypes == null || licenseTypes == "") {
//                alert("未填写许可类别!");
//                return;
//            }
//            if ((licenseRemark == null || licenseRemark == "") && licenseTypes == '5') {
//                alert("请填写说明!");
//                return;
//            }

            result.put("licenseStartTime",licenseStartTime);
            result.put("licenseEndTime",licenseEndTime);
            result.put("licenseDocumentsNeme",licenseDocumentsNeme);
            result.put("licenseDocumentsCode",licenseDocumentsCode);
            result.put("licenseType",licenseType);
            result.put("licenseRemark",licenseRemark);
            result.put("licenseCertificateNeme",licenseCertificateNeme);
            result.put("licenseCertificateCode",licenseCertificateCode);
        }
        //当办件类型为咨询时，获取咨询答复内容
        if(eventType.equals( "2C" )){
            String replyContent = document.select( "#replyContent" ).attr( "value" );
            result.put("replyContent",replyContent);
        }

        return result;

    }

    /**
     * 获取提交流程审批意见
     * @param type
     * @return
     */
    private static Map<String, String> getSpIdea(String type,Element formDatas) {
        Map<String, String> result = new HashMap<>();
        // 意见相关
        String auditAdvice = "1";
        String auditAdviceName = "同意";
        String auditRemark = "同意";
        String logOperType = ""; // 日志操作类型
        if (type == "1") { // 受理
            auditAdvice = "1";
            auditAdviceName = "受理";
            auditRemark = "受理";
            logOperType = "ACCEPT";
        } else if (type == "6") {
            auditAdvice = "1";
            auditAdviceName = "受理并办结";
            auditRemark = "受理并办结";
            logOperType = "ACCEPT";
        } else if (type == "7") { // 提交审核意见
            auditAdvice = "1";
            auditAdviceName = "提交审核意见";
            auditRemark = "同意受理";
            logOperType = "AUDIT";
//
//            if (auditRemark == null || auditRemark == "") {
//                alert("请先填写拟办意见!");
//                return;
//            }
        } else if (type == "8") { // 决定（审批）的提交
            auditAdvice = "1";//$("#auditAdvice").textbox("getValue");
            auditAdviceName ="同意";// $("#auditAdvice").textbox("getText");
            auditRemark = "同意";
            logOperType = "APPROVAL";
            Elements pickupTypeRadio = formDatas.select("input[name='pickupType']");
            String pickupType = JsoupSelfUtil.getRadioVal(pickupTypeRadio);//1：现场取件，2：物流

            String jdStatus = formDatas.select( "#jdStatus" ).attr( "value" );
            boolean state = StringUtils.isNotEmpty( jdStatus )
                    && jdStatus.equals( "1" )
                    && auditAdvice.equals( "0")
                    && (pickupType.equals( "1") || pickupType.equals( "3") );
            if(state){
                //TODO
//                if (!checkOutPickUpInfo()) {
//                    return
//                }
            }
        } else if (type == "back") { // 回退退回
            auditAdvice = "2";
            auditAdviceName = "回退退回";
            auditRemark = "";
            logOperType = "ROLLBACK";
        } else if (type == "9") { // 制证：制作结束
            auditAdvice = "1";
            auditAdviceName = "制证";
            auditRemark = "";
            logOperType = "MAKECER";
        } else if (type == "10") { // 取件
            auditAdvice = "1";
            auditAdviceName = "取件";
            auditRemark = "";
            logOperType = "PICKUP";
        } else if (type == "11") {
            auditAdvice = "1";
            auditAdviceName = "收费成功";
            auditRemark = "";
            logOperType = "CHARGE";
        }

        result.put( "auditAdvice",auditAdvice );
        result.put( "auditAdviceName",auditAdviceName );
        result.put( "auditRemark",auditRemark );
        result.put( "logOperType",logOperType );

        return result;
    }

    /**
     * 办理流程
     * @param token
     * @param decision no:终止流程，back：回退退回， 默认是空，往下执行
     * @param document
     * @return
     */
    public static String handleTask(String token, String decision, Document document) throws IOException {

        Map<String,String> formParam = new HashMap<>();

        String  taskId = document.select( "#taskId" ).attr( "value" );
        String shardKey = document.select( "#shardKey" ).attr( "value" );
        String nodeId = document.select( "#nodeId" ).attr( "value" );
        String busiId = document.select( "#id" ).attr( "value" );
        // 统一社会信用代码
        String busiDeptCode = document.select( "#performDeptCode" ).attr( "value" );
        // 部门名称
        String busiDeptName = document.select( "#implDeptName" ).attr( "value" );

        formParam.put( "procTaskId" ,taskId);
        formParam.put( "shardKey" ,shardKey);
        formParam.put( "nextNodeId" ,nodeId);
        formParam.put( "decision" ,decision);
        formParam.put( "busiDeptCode" ,busiDeptCode);
        formParam.put( "busiDeptName" ,busiDeptName);
        // 当流程上没有配置人的时候，通过这个标志，为固定角色产生待办任务：1-依申请、2-主动行使
        formParam.put( "BIZ_PROP_DO_CASE_TYPE" ,"1");
        if (decision.equals( "back" )) { // 回退退回
            String processInstanceId = document.select( "#procInstId" ).attr( "value" );
            formParam.put( "processInstanceId", processInstanceId );
            formParam.put( "callbackType", "-1" );
            WorkflowUtil.jumpTask( token,formParam);
        }else if(decision.equals( "no" )){// 结束流程
            String processInstanceId = document.select( "#procInstId" ).attr( "value" );
            formParam.put( "processInstanceId", processInstanceId );
            formParam.put( "callbackType", "0" );
            // 生成办结通知书
            String responeBody = ViewTaskUtil.generateAndViewBJNotice( token,busiId);
            JSONObject jsonObject = JSONObject.parseObject(responeBody);
            boolean success = jsonObject.getBoolean("success");
            if(success){
                // 结束流程
                //联审层级
                String tripleReviewLevelCode =document.select( "#tripleReviewLevelCode" ).attr( "value" );
                //是否进行联审
                String isJointTrail = document.select( "#isJointTrail" ).attr( "value" );
                String affairParallelCode = document.select( "#affairParallelCode" ).attr( "value" );
                if(StringUtils.isNotEmpty( affairParallelCode ) && StringUtils.isNotEmpty(affairParallelCode)){
                    batchJumpTaskForParallel(token,busiId);
                }else if(StringUtils.isNotEmpty( tripleReviewLevelCode )
                        && StringUtils.isNotEmpty(isJointTrail )
                && isJointTrail.equals( "1")){
                    //判断是否为三级联审件，如果是三级联审件则将另外层级的流程同样结束,批量结束流程
                    ViewTaskUtil.batchJumpTask(token,busiId);
                }else{
                    WorkflowUtil.jumpTask( token,formParam );
                }
            }
        }else{ // 往下执行
            // 如果是最后一个节点，生成办结通知书
            String isBJNotice = document.select( "#isBJNotice" ).attr( "value" );
            if(isBJNotice.equals( "true" )){
                String responeBody = ViewTaskUtil.generateAndViewBJNotice( token,busiId);
                JSONObject jsonObject = JSONObject.parseObject(responeBody);
                boolean success = jsonObject.getBoolean("success");
                if(success){
                    Map<String,String> preParam = new HashMap<>(  );
                    preParam.put( "decision",decision );
                    ViewTaskUtil.preCompleteTask(token,preParam,document); // 准备提交任务
                }
            }else{
                Map<String,String> preParam = new HashMap<>(  );
                preParam.put( "decision",decision );
                ViewTaskUtil.preCompleteTask(token,preParam,document); // 准备提交任务
            }

        }

        return null;
    }

    private static void batchJumpTaskForParallel(String actCookie, String affairId) throws IOException {
        Map<String,String> formParam = new HashMap<>();
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/getParallelAffair";
        formParam.put( "affairId",affairId );
        String responeBody = WestarHttpUtil.postMethod(url,actCookie ,formParam );
        JSONObject reg = JSONObject.parseObject(responeBody);
        boolean isParallelAffair = reg.getBoolean("isParallelAffair");
        if(isParallelAffair){

            JSONArray affairList  = reg.getJSONArray( "data" );
            JSONArray taskList   = reg.getJSONArray( "taskIdList" );
            if(null!=affairList && !affairList.isEmpty()){
                for (int i=0,len =affairList.size();i<len;i++ ){
                    // 结束流程
                    Map<String,String> formParamForbatch = new HashMap<>();

                    JSONObject jsonObject = affairList.getJSONObject( i );
                    String procTaskId = taskList.getString( i );

                    formParamForbatch.put("processInstanceId",jsonObject.getString( "wfInstanceId" )  );
                    formParamForbatch.put("procTaskId",procTaskId );
                    formParamForbatch.put("shardKey",jsonObject.getString( "shardKey" )  );
                    formParamForbatch.put("busiDeptCode",jsonObject.getString( "performDeptCode" )  );
                    formParamForbatch.put("busiDeptName",jsonObject.getString( "implDeptName" )  );
                    formParamForbatch.put("BIZ_PROP_DO_CASE_TYPE","1" );
                    formParamForbatch.put("callbackType","0" );

                    WorkflowUtil.jumpTask( actCookie,formParamForbatch );
                }
            }
        }

    }

    public static boolean preCompleteTask(String token,Map<String,String> preParam,Document document) throws IOException {

        Map<String,String> formParam = new HashMap<>();

        String  taskId = document.select( "#taskId" ).attr( "value" );
        String shardKey = document.select( "#shardKey" ).attr( "value" );
        //TODO 需要确认一下
        String nextNodeId = document.select( "#nextNodeId_" ).attr( "value" );
        String nextHandlerJSON = document.select( "#nextHandlerJSON_" ).attr( "value" );
        String busiId = document.select( "#id" ).attr( "value" );
        // 统一社会信用代码
        String busiDeptCode = document.select( "#performDeptCode" ).attr( "value" );
        // 部门名称
        String busiDeptName = document.select( "#implDeptName" ).attr( "value" );

        formParam.put( "procTaskId" ,taskId);
        formParam.put( "shardKey" ,shardKey);
        formParam.put( "nextNodeId" ,nextNodeId);
        formParam.put( "nextHandler" ,nextHandlerJSON);
        formParam.put( "busiDeptCode" ,busiDeptCode);
        formParam.put( "busiDeptName" ,busiDeptName);
        // 当流程上没有配置人的时候，通过这个标志，为固定角色产生待办任务：1-依申请、2-主动行使
        formParam.put( "BIZ_PROP_DO_CASE_TYPE" ,"1");

        //新案件提交
        String eLStr = document.select( "#elCondition_" ).attr( "value" );
        if(StringUtils.isNotEmpty(eLStr)){
            String[] els = eLStr.split("==");
            if(els.length == 2){
                formParam.put( els[0] , els[1] );
            }
        }

        String checkedUsers = document.select( "#applyUsersLoginId_" ).attr( "value" );
        String checkedDepts = document.select( "#applyUsersDeptCode_" ).attr( "value" );
        formParam.put( "appointUserId " , checkedUsers );
        formParam.put( "appointGroupId  " , checkedDepts );
        formParam.put( "isSendSMS  " , "" );
        if(null != preParam && !preParam.isEmpty()){
            formParam.putAll(preParam);
        }
        // 提交任务
        boolean success = WorkflowUtil.completeTask(token,formParam);
        return success;

    }

    //生成并预览办结通知书

    public static String generateAndViewBJNotice(String actCookie,String affairId) throws IOException {
        String url = "http://"+ SysConst.DOMAIN + "/dothingsui/affair/handle/" + affairId + "/5";
        String responeBody = WestarHttpUtil.postMethod( url,actCookie,null );
        return responeBody;
    }

    /**
     * 批量结束流程，三级联审单据，如果一个层级出现不同意，则将关联的单据流程都直接结束
     * @param actCookie
     * @param affairId
     * @return
     * @throws IOException
     */
    public static String batchJumpTask(String actCookie,String affairId) throws IOException {
        String url = "http://"+ SysConst.DOMAIN + "/dothingsui/affair/getTripleReviewAffair.do";
        Map<String,String> postParam = new HashMap<>( );

        postParam.put("affairId",affairId);
        String responeBody = WestarHttpUtil.postMethod(url,actCookie ,postParam );
        JSONObject reg = JSONObject.parseObject(responeBody);
        boolean successes = reg.getBoolean("successes");
        if(successes){

            JSONArray affairList  = reg.getJSONArray( "listData" );
            if(null!=affairList && !affairList.isEmpty()){
                for (int i=0,len =affairList.size();i<len;i++ ){
                    // 结束流程
                    Map<String,String> formParamForbatch = new HashMap<>();

                    JSONObject jsonObject = affairList.getJSONObject( i );

                    formParamForbatch.put("processInstanceId",jsonObject.getString( "wfInstanceId" )  );
                    formParamForbatch.put("procTaskId",jsonObject.getString( "remark" ) );
                    formParamForbatch.put("shardKey",jsonObject.getString( "shardKey" )  );
                    formParamForbatch.put("busiDeptCode",jsonObject.getString( "performDeptCode" )  );
                    formParamForbatch.put("busiDeptName",jsonObject.getString( "implDeptName" )  );
                    formParamForbatch.put("BIZ_PROP_DO_CASE_TYPE","1" );
                    formParamForbatch.put("callbackType","0" );

                    WorkflowUtil.jumpTask( actCookie,formParamForbatch );
                }
            }
        }
        return null;
    }

    public static void make(String token, String parentPage, String type) {
//        if (type == 1) {
//            makeLicense()
//        } else if (type == 2) {
//            makeDocument()
//        } else if (type == 3) {
//            acceptAndOver();
//        }
    }

    /**
     * 查询办件是否归档
     * @param actCookie
     * @param affairCode
     * @return
     * @throws IOException
     */
    public static boolean listAffairData(String actCookie, String affairCode) throws IOException {
        //获取页面必填信息
        Map<String,String> neededParam = getAffairFinishInfo(actCookie);

        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/listAffairData";
        Map<String,String> searchParam = new HashMap<>(  );
        searchParam.putAll(neededParam);
        searchParam.put("page","1"  );
        searchParam.put("rows","10"  );
        searchParam.put("busiAlias","COMMON-MODEL"  );
        searchParam.put("status","20"  );
        searchParam.put("isScene","0"  );
        searchParam.put("affairCode",affairCode  );
        searchParam.put("eventName",""  );
        searchParam.put("applicantName",""  );
        searchParam.put("applicantIdCard",""  );
        searchParam.put("applyType",""  );
        searchParam.put("eventType",""  );
        searchParam.put("deptIds",""  );
        searchParam.put("startTime",""  );
        searchParam.put("endTime",""  );
        String responeBody = WestarHttpUtil.postMethodWithFull(url,actCookie,searchParam);

        JSONObject jsonObject = JSON.parseObject(responeBody);
        Integer total = jsonObject.getInteger( "total" );
        return total == 1;
    }
    /**
     * 查询办件是否草稿
     * @param actCookie
     * @param affairCode
     * @return
     * @throws IOException
     */
    public static boolean listAffairTodoData(String actCookie, String affairCode) throws IOException {
        //获取页面必填信息
        Map<String,String> neededParam = getAffairFinishInfo(actCookie);

        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/listData?applyType=0&busiType=1";
        Map<String,String> searchParam = new HashMap<>(  );
        searchParam.putAll(neededParam);
        searchParam.put("applicantName",""  );
        searchParam.put("affairCode",affairCode  );
        searchParam.put("eventName",""  );
        searchParam.put("eventType",""  );
        searchParam.put("page","1"  );
        searchParam.put("rows","10"  );
        String responeBody = WestarHttpUtil.postMethodWithFull(url,actCookie,searchParam);

        JSONObject jsonObject = JSON.parseObject(responeBody);
        Integer total = jsonObject.getInteger( "total" );
        return total == 1;
    }

    /**
     * 获取用于查询已办数据的shardKey
     * @param actCookie
     * @return
     */
    private static Map<String,String> getAffairFinishInfo(String actCookie) {
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/wfDoRecord/listCompleteTaskpage";
        Map<String,String> map = new HashMap<>();
        try {
            String responeBody = WestarHttpUtil.getMethod(url,actCookie,null);
            Document doc = Jsoup.parse(responeBody);
            Elements form = doc.select("#form-data");

            String handlerId = form.select( "#handlerId").attr("value");
            String shardKey = form.select( "#shardKey").attr("value");
            String areaCode = form.select( "#userAreaCode").attr("value");
            map.put("handlerId",handlerId);
            map.put("shardKey",shardKey);
            map.put("areaCode",areaCode);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;

    }
}
